package com.ceprei.gui.shiro.jwt;

import com.ceprei.domain.modules.sys.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClaims;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * @author Administrator
 */
@Slf4j
public class JwtTokenUtil implements Serializable {

    //    private static final String CLAIM_KEY_USER_ID = "id";
    public static final String CLAIM_KEY_USERNAME = "sub";
    public static final String CLAIM_KEY_CREATE_TIME = "create_time";

    public static String getUsernameFromToken(String secret, String token) {
        String username;
        try {
            final Claims claims = getClaimsFromToken(secret, token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    public static Claims getClaimsFromToken(String secret, String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    /**
     * 获取凭证
     *
     * @param secret 秘钥
     * @param user   用户信息
     * @return 凭证
     */
    public static String generateToken(String secret, User user) {
        DefaultClaims defaultClaims = new DefaultClaims();
        defaultClaims.put(CLAIM_KEY_USERNAME, user.getLoginName());
        return generateToken(secret, defaultClaims);
    }

    /**
     * 获取凭证
     *
     * @param secret 秘钥
     * @param claims 凭证信息
     * @return 凭证
     */
    public static String generateToken(String secret, Claims claims) {
        try {
            return createToken(secret, claims);
        } catch (Exception e) {
            log.error("generate token is fail!", e);
            return null;
        }
    }

    /**
     * 创建凭证
     *
     * @param secret 秘钥
     * @param claims 凭证信息
     * @return token
     */
    private static String createToken(String secret, Claims claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
}
